<?php
namespace app\api\controller\v1;

use app\common\controller\Api;
use think\exception\ValidateException;
use Qcloud\Cos\Client;

class Upload extends Api
{
    /**
     * 返回无BOM的JSON响应
     * @param array $data
     * @return \think\Response
     */
     // 无需鉴权的方法
    protected $noNeedLogin = ["upload"];
    protected $noNeedRight = ["upload"];

    public function upload()
    {
        try {
            // 获取上传的文件数组
            $files = $this->request->file('file');
            if (!$files || !is_array($files)) {
                throw new ValidateException('未检测到上传文件或文件参数格式错误');
            }

            // 读取腾讯云 OSS 配置
            $Config = config('oss');
            if (!isset($Config['SecretId'], $Config['SecretKey'], $Config['bucket'])) {
                throw new \Exception('OSS 配置不完整');
            }
            $secretId = $Config['SecretId'];
            $secretKey = $Config['SecretKey'];
            $bucket = $Config['bucket'];

            $uploadedUrls = [];

            // 配置腾讯云 COS
            $cosClient = new Client([
                'region' => 'ap-guangzhou', // 替换为你的 COS 区域
                'credentials' => [
                    'secretId' => $secretId,
                    'secretKey' => $secretKey,
                ],
            ]);

            // 限制最大文件数量
            if (count($files) > 5) {
                throw new ValidateException('最多允许上传 5 个文件');
            }

            foreach ($files as $file) {
                // 验证每个文件
                //validate(['fileSize:10485760|fileExt:jpg,png,gif,txt,pdf,doc,docx'])->check($file);

                // 获取文件信息
                $filePath = $file->getRealPath();
                $info=$file->getInfo();
                $fileName = uniqid() . '.' . preg_replace("/^.*\./isx","",$info['name']); // 唯一文件名
                $key = "upload/images/".date("Y-m-d")."/".$fileName;

                // 上传文件到 COS
                $result = $cosClient->upload(
                    $bucket,
                    $key,
                    fopen($filePath, 'rb')
                );

                if (isset($result['Location']) && is_string($result['Location'])) {
                    $uploadedUrls[] = "https://".preg_replace("/^.*\.myqcloud\.com/Uisx","tcimg.yangjc.com",$result['Location']);
                } else {
                    throw new \Exception('文件上传失败: 未返回有效的 ObjectURL');
                }
            }

            // 返回成功信息
           echo json_encode(["code" => 1, "msg" => "上传成功", "data" => [
               "urls" => $uploadedUrls
           ]]);
            exit;
        } catch (ValidateException $e) {
            return $this->jsonResponse(["code" => 0, "msg" => $e->getMessage()]);
        } catch (\Exception $e) {
            return $this->jsonResponse(["code" => 0, "msg" => "上传失败: " . $e->getMessage()]);
        }
    }
}
